import UIKit
import SnapKit

extension Bundle {
    var appName: String {
        return object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
            ?? object(forInfoDictionaryKey: "CFBundleName") as? String
            ?? "App"
    }
}

class AgreementView: UIView {

    lazy var agreeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(systemName: "circle")?.withTintColor(UIColor(hex: "#CAFE67"), renderingMode: .alwaysOriginal), for: .normal)
        button.setImage(UIImage(systemName: "checkmark.circle.fill")?.withTintColor(UIColor(hex: "#CAFE67"), renderingMode: .alwaysOriginal), for: .selected)
        button.addAction {
            [weak self] in
            self?.agreeButton.isSelected.toggle()
         }
        return button
    }()

    private let agreementLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 10)
        label.numberOfLines = 0
        label.textColor = .white

        let text = "登录注册代表您已同意《用户服务协议》并授权“\(Bundle.main.appName)”获取手机号"
        let attributedString = NSMutableAttributedString(string: text)
        if let linkRange = text.range(of: "《用户服务协议》") {
            let nsRange = NSRange(linkRange, in: text)
            attributedString.addAttribute(.foregroundColor, value: UIColor(hex: "#CAFE67"), range: nsRange)
        }

        label.attributedText = attributedString
        label.isUserInteractionEnabled = true
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        addSubview(agreeButton)
        addSubview(agreementLabel)

        agreeButton.snp.makeConstraints { make in
            make.left.centerY.equalToSuperview()
        }

        agreementLabel.snp.makeConstraints { make in
            make.left.equalTo(agreeButton.snp.right).offset(3)
            make.right.equalToSuperview().offset(-10)
            make.top.bottom.equalToSuperview()
        }

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(agreementTapped))
        agreementLabel.addGestureRecognizer(tapGesture)
    }

    @objc private func agreementTapped() {
        let vc = WebViewController(url: "https://home.cqbbx.cn/web/agreement/serviceAgreement.html")
        findViewController()?.navigationController?.push(vc)
    }
}
